import {
  login,
  getUserAllInfo,
  setStaffPosition,
  setStaffArea
} from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { encrypt } from '@/utils/jsencrypt'

const state = {
  token: getToken(),
  user: {},
  curArea: {}, // 当前园区
  curPosition: {} // 当前角色
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER: (state, user) => {
    state.user = user
  },
  SET_AREA: (state, area) => {
    state.curArea = area
  },
  SET_POSITION: (state, position) => {
    state.curPosition = position
  }
}

const actions = {
  // user login
  login ({ commit, dispatch }, userInfo) {
    const { username, password } = userInfo

    return new Promise((resolve, reject) => {
      login({ mobile: username.trim(), password: encrypt(password) })
        .then((response) => {
          const ticket = response
          commit('SET_TOKEN', ticket)
          setToken(ticket)
          dispatch('getAllInfo')
          resolve(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // get user info
  //  flag: 是否只是切换岗位，判改变当前院所，false为改变，true为不改变
  async getAllInfo ({ commit, state, dispatch }, flag = false) {
    return new Promise((resolve, reject) => {
      getUserAllInfo()
        .then(async (response) => {
          if (!response) {
            reject('校验错误，请重新登录')
          }

          const {
            role,
            area,
            areaList,
            menuList,
            platformList,
            positions,
            staff,
            roles,
            isGroupAdmin
          } = response

          if (!areaList || areaList.length < 1) {
            reject('当前账号没有绑定园所，请联系管理员')
          }
          // roles must be a non-empty array
          if (roles && roles.length > 0) {
            commit('SET_POSITION', role || roles[0])
          }

          // 是否改变当前园所
          if (!flag) {
            commit('SET_AREA', area || areaList[0])
          }

          // 保存用户信息
          commit('SET_USER', {
            ...staff,
            positions,
            platformList,
            areaList,
            roles,
            isGroupAdmin
          })

          // 重置路由
          if (menuList) {
            resetRouter()

            // generate accessible routes map based on roles
            const addRoutes = await dispatch(
              'permission/generateRoutes',
              menuList,
              { root: true }
            )
            // dynamically add accessible routes
            router.addRoutes(addRoutes)

            // reset visited views and cached views
            flag && dispatch('tagsView/delAllViews', null, { root: true })
          }

          resolve({ menuList })
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // 切换园区
  setStaffArea ({ dispatch }, params) {
    console.log(params)
    return new Promise((resolve) => {
      setStaffArea(params).then((res) => {
        if (res) {
          dispatch('getAllInfo', false)
          resolve()
          location.reload()
        }
      })
    })
  },

  // 切换岗位
  setStaffPosition ({ dispatch }, params) {
    console.log(params)
    return new Promise((resolve) => {
      setStaffPosition(params).then((res) => {
        if (res) {
          dispatch('getAllInfo', true)
          resolve()
        }
      })
    })
  },

  // user logout
  logout ({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resetRouter()

      // reset visited views and cached views
      // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      dispatch('tagsView/delAllViews', null, { root: true })
      router.push('/user/login')
      resolve()
      // logout(state.token).then(() => {
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // remove token
  resetToken ({ commit }) {
    return new Promise((resolve) => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  setToken ({ commit }, token) {
    return new Promise((resolve) => {
      console.log(token)
      commit('SET_TOKEN', token)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
